package com.lap.framework.resources.utils;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <pre>
 * URI 工具类
 * </pre>
 *
 * @author Shuisheng.Lao
 * @version 1.0.0
 */
public final class UriUtils {
    private static final String SLASH = "/";
    private static final String REGEX = "\\{\\w+\\}";
    private static final String UNDER_LINE = "_";
    private static final String LINE = "-";

    private UriUtils() {
    }

    /**
     * <pre>
     *  获取URI
     * </pre>
     *
     * @param uri URI
     * @return 集合
     */
    public static String getUri(String[] uri) {
        if (Objects.nonNull(uri) && uri.length > 0) {
            if (!uri[0].startsWith(SLASH)) {
                return SLASH + uri[0];
            } else {
                return uri[0];
            }
        }
        return "";
    }

    /**
     * <pre>
     *  获取uri_code
     * </pre>
     *
     * @param module 模块
     * @param uri    URI
     * @param method 方法
     * @return URI编码
     */
    public static String getUriCode(String module, String uri, String method) {
        StringBuilder sb = new StringBuilder();
        if (!isEmpty(module)) {
            sb.append(module).append(UNDER_LINE);
        }
        if (!isEmpty(method)) {
            sb.append(method.toLowerCase());
        }
        if (!isEmpty(uri)) {
            Pattern pattern = Pattern.compile(REGEX);
            Matcher matcher = pattern.matcher(uri);
            String newUri = matcher.replaceAll("id");
            newUri = newUri.replace(SLASH, UNDER_LINE);
            newUri = newUri.replace(LINE, UNDER_LINE);
            sb.append(newUri);
        }
        return sb.toString();
    }

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    /**
     * <pre>
     *  类转换到URI
     * </pre>
     *
     * @param className 类名
     * @return 返回URI
     */
    public static String getTypeUri(String className) {
        StringBuilder sb = new StringBuilder();
        if (!isEmpty(className)) {
            char[] array = className.toCharArray();
            for (int index = 0, size = array.length; index < size; index++) {
                if (index != 0 && Character.isUpperCase(array[index])) {
                    sb.append(UNDER_LINE);
                }
                sb.append(Character.toLowerCase(array[index]));
            }
        }
        return sb.toString();
    }

}
